package org.grayrabbit.cms.plugin;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.grayrabbit.cms.plugin.PluginManagerState;
import org.grayrabbit.cms.plugin.PluginStateStore;
import org.grayrabbit.cms.properties.ApplicationProperties;


/**
 * @author sys53
 * @version 1.0
 * @created 06-一月-2012 16:50:23
 */
public class CmsPluginStateStore implements PluginStateStore {

	private ApplicationProperties applicationProperties;
	private Collection<String> keys;

	public CmsPluginStateStore(ApplicationProperties applicationProperties){
		this.applicationProperties = applicationProperties;
		reloadKeys();
	}

	private void reloadKeys() {
		Collection<String> stringsWithPrefix = this.applicationProperties.getStringsWithPrefix("jira.plugin.state-");
	    if (stringsWithPrefix != null)
	    {
	      this.keys = Collections.unmodifiableCollection(stringsWithPrefix);
	    }
	    else
	    {
	      this.keys = Collections.emptyList();
	    }
	}

	public PluginManagerState loadPluginState(){
		Map<String,Boolean> map = new HashMap<String, Boolean>();
		for(String key : keys){
			map.put(key.substring("jira.plugin.state-".length()+1), Boolean.valueOf(this.applicationProperties.getString(key)));
		}
		return new PluginManagerState(map);
	}

	/**
	 * 
	 * @param pluginManagerState
	 */
	public synchronized void savePluginState(PluginManagerState state){
		for(String key : keys){
			applicationProperties.setString(key, null); //清空所有key 对应的键值;
		}
		for(String key :  state.getMap().keySet()){
			if(state.getMap().get(key)!=null){
				this.applicationProperties.setString("jira.plugin.state-." + key,state.getMap().get(key).toString());
			}
		}
	}

}